package chapter1.socket.task1;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/*
3:修改我的文件发送服务器功能，可以从客户端接受文件；
步骤如下： 1）收到服务端发来的文件名
          2）保存到某个目录下（目录自定义）
	      3）给客户端发送成功或者失败的提示
 */
public class Task3_Client {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 9999);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            OutputStream out = socket.getOutputStream();
            String fileName = in.readLine();
            File file = new File(FOLDER, fileName);
            if (file.exists() == false || file.canRead() == false)
                out.write(0);
            else {
                out.write(1);
                FileInputStream fin = new FileInputStream(file);
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = fin.read(b)) > -1)
                    out.write(b, 0, len);
                out.flush();
                socket.shutdownOutput();
                System.out.println(in.readLine());
                fin.close();
            }
            System.out.println(socket + "over");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static final String FOLDER = "F:\\123";   
}
